package com.mrjy.coursepackage.bo;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.mrjy.common.entity.CoursePackageInfo;
import com.mrjy.common.entity.CoursePackageVip;
import com.mrjy.common.entity.MessageInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.VideoVip;
import com.mrjy.common.redis.RedisPool;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.coursepackage.dao.ICoursePackageInfoDao;
import com.mrjy.coursepackage.dao.ICoursePackageVideoRelDao;
import com.mrjy.coursepackage.dao.ICoursePackageVipDao;
import com.mrjy.coursepackage.dto.CoursePackageInfoDTO;
import com.mrjy.coursepackage.dto.CoursePackageVipDTO;
import com.mrjy.maintain.dao.IMessageInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.video.dao.IVideoVipDao;
import com.mrjy.wechat.conts.WxConsts;
import com.mrjy.wechat.util.WeChatUtil;

/**
 * 课程包购买信息 业务实现类
 * @author csshui
 *
 */
@Service("coursePackageVipBo")
public class CoursePackageVipBo implements ICoursePackageVipBo {

	@Resource
	private ICoursePackageVipDao coursePackageVipDao;
	@Resource
	private IMessageInfoDao messageInfoDao;
	@Resource
	private IUserInfoDao userInfoDao;
	@Resource
	private ICoursePackageVideoRelDao coursePackageVideoRelDao;
	@Resource
	private ICoursePackageInfoDao coursePackageInfoDao;
	@Resource
	private RedisPool redisPool;
	@Resource
	private IVideoVipDao videoVipDao;
	
	@Override
	public Object txInsert(CoursePackageVip info) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = coursePackageVipDao.insert(info);
		if (count > 0 ) {
			map.put("err_code", 0);
			map.put("err_msg", "插入成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "插入失败");
		}
		return map;
	}

	@Override
	public Object txUpdate(CoursePackageVip info) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = coursePackageVipDao.update(info);
		if (count > 0 ) {
			map.put("err_code", 0);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "更新失败");
		}
		return map;
	}

	@Override
	public Object txUpdateById(CoursePackageVip info) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count =  coursePackageVipDao.updateById(info);
		if (count > 0 ) {
			map.put("err_code", 0);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "更新失败");
		}
		return map;
	}

	@Override
	public Object txDelete(Integer id) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count =  coursePackageVipDao.delete(id);
		if (count > 0 ) {
			map.put("err_code", 0);
			map.put("err_msg", "删除成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "删除失败");
		}
		return map;
	}

	@Override
	public Object selectById(Integer id) {
		Map<String, Object> map = new HashMap<String, Object>();
		CoursePackageVip info = coursePackageVipDao.selectById(id);
		if ( null != info ) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("info", info);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "查询失败");
			map.put("info", info);
		}
		return map;
	}

	@Override
	public Object isCoursePackageVip(CoursePackageVip info) {
		Map<String, Object> map = new HashMap<String, Object>();
		info.setIsVipStatus(1);
		info.setDisableFlag(0);
		List<CoursePackageVip> list = coursePackageVipDao.isCoursePackageVip(info);
		if ( null != list &&  list.size() > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "有购买过课程包");
			map.put("list", list);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "没有购买过课程包");
		}
		return map;
	}
	
	@Override
	public Object txCheckCoursePackageVipExpired() {
		Map<String , Object> map = new HashMap<String, Object>();
		//1.先检查课程包会员过期的记录，并将会员状态is_vip_status=1 改成 临时状态is_vip_status=2
		coursePackageVipDao.updateCheckCoursePackageVipExpired();
		//2.查出刚刚过期的记录，并添加提醒消息
		List<CoursePackageVipDTO> list = coursePackageVipDao.selectCoursePackageVipExpired();
		if(null == list || list.size() == 0){
			map.put("err_code",1);
			map.put("err_msg", "没有过期课程包会员的数据");
		}else{
			CoursePackageInfo coursePackageInfo = new CoursePackageInfo();
			for (CoursePackageVipDTO vipDTO :list) {
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setTitle("会员到期信息");
				
				messageInfo.setContent("您购买的【"+ vipDTO.getCoursePackageName() +"】已经到期，如想继续免费观看该课程包");
				messageInfo.setSendTime(new Date());
				messageInfo.setSenderId(1);
				messageInfo.setUserId(vipDTO.getUserId());
				messageInfo.setReadTag(0);
				messageInfo.setMsgModule(5);
				messageInfo.setCostId(vipDTO.getCoursePackageId());
				messageInfo.setEndTime(new Timestamp(vipDTO.getExpireTime().getTime()));
				messageInfoDao.insert(messageInfo);
				
				//4.去除redis中用户相应的视频观看权限 
				String vids = redisPool.get(GlobalConstant.USER_VIDEO_VIP+vipDTO.getUserId()); //用户拥有观看权限的视频 ("8,17,23")
				coursePackageInfo.setId(vipDTO.getCoursePackageId());
				List<CoursePackageInfoDTO> vlist = coursePackageInfoDao.selectVideoListById(coursePackageInfo);
				VideoVip videoVip = new VideoVip();
				for (CoursePackageInfoDTO infoDTO : vlist) {
					//判断用户是否是该单节微课会员(videoVip)
					videoVip.setUserId(vipDTO.getUserId());
					videoVip.setVideoId(infoDTO.getVideoId());
					videoVip.setIsVipStatus(1);//是微课会员
					videoVip.setDisableFlag(0);
					VideoVip vip = videoVipDao.selectByUserIdAndVideoId(videoVip);
					if (vip == null) {
						//如果不是微课会员,就直接去除该视频观看权限
						vids = vids.replace(infoDTO.getVideoId()+",", "");
					}
				}
				redisPool.set(GlobalConstant.USER_VIDEO_VIP+vipDTO.getUserId(), vids);
			}
			//3.把临时状态为2的修改为0，变成非会员
			int count = coursePackageVipDao.updateCoursePackageVipExpired();
			map.put("err_code",0);
			map.put("err_msg", "已向"+  count  +"位用户发送会员到期提醒");
		}	
		
		return map;
	}

	@Override
	public Object checkCoursePackageVipWillExpire(int numDate) {
		Map<String,Object> map = new HashMap<String,Object>();
		//1.查询离会员过期还有numDate天的记录，并添加我的消息提醒
		List<CoursePackageVipDTO> list= coursePackageVipDao.selectCoursePackageVipWillExpire(numDate);
		if(null == list || list.size() == 0){
			map.put("err_code",1);
			map.put("err_msg", "没有离过期还有" + numDate + "天的数据");
		}else{
			for (CoursePackageVipDTO dto : list) {
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setTitle("会员即将到期");
				messageInfo.setContent("您购买的【"+ dto.getCoursePackageName()  +"】已经即将到期（"+ dto.getExpireTimeString() +" 到期）");
				messageInfo.setSendTime(new Date());
				messageInfo.setSenderId(1);
				messageInfo.setUserId(dto.getUserId());
				messageInfo.setReadTag(0);
				messageInfo.setMsgModule(5);
				messageInfo.setCostId(dto.getCoursePackageId());
				messageInfo.setEndTime(new Timestamp(dto.getExpireTime().getTime()));
				messageInfoDao.insert(messageInfo);
			}
			map.put("err_code",0);
			map.put("err_msg", "已向"+  list.size()  +"位用户发送课程包会员即将到期提醒");
		}
		
		return map;
	}

	@Override
	public Object isCoursePackageVipByVideoIdAndUserId(CoursePackageVipDTO info) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<CoursePackageVipDTO> list = coursePackageVipDao.isCoursePackageVipByVideoIdAndUserId(info);
		if ( null != list &&  list.size() > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "有购买过课程包");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "没有购买过课程包");
			map.put("rows", list);
		}
		return map;
	}

	@Override
	public Object checkCoursePackageVipWillExpire3Day(int numDate) {
		Map<String,Object> map = new HashMap<String,Object>();
		//1.查询离会员过期还有numDate天的记录，并发送微信消息提醒
		List<CoursePackageVipDTO> list= coursePackageVipDao.selectCoursePackageVipWillExpire(numDate);
		if(null == list || list.size() == 0){
			map.put("err_code",1);
			map.put("err_msg", "没有离过期还有" + numDate + "天的数据");
		}else{
			UserInfo ui = null ;
			for (CoursePackageVipDTO dto : list) {
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setTitle("会员即将到期");
				messageInfo.setContent("您购买的【"+ dto.getCoursePackageName()  +"】已经即将到期（"+ dto.getExpireTimeString() +" 到期）");
				messageInfo.setSendTime(new Date());
				messageInfo.setSenderId(1);
				messageInfo.setUserId(dto.getUserId());
				messageInfo.setReadTag(0);
				messageInfo.setMsgModule(5);
				messageInfo.setCostId(dto.getCoursePackageId());
				messageInfo.setEndTime(new Timestamp(dto.getExpireTime().getTime()));
				messageInfoDao.insert(messageInfo);
				
				
				if(dto.getUserId() != null){
					ui = userInfoDao.queryById(dto.getUserId());
					if(ui != null && StringUtils.isNotBlank(ui.getWeixinOpenid())){
						//根据课程包id查询其第一节课的vid
						int vid = coursePackageVideoRelDao.selectByCoursePackageIdAndSort(dto.getCoursePackageId());
						WeChatUtil.sendWechatTemplateMessageExpireCourcePackageVip(ui.getUserName(),
								dto.getCoursePackageName() , dto.getExpireTimeString() 
								,WxConsts.PUBLIC_DOMAIN + "/index.html?from=weClasses/course_detail.html@_@vid="+vid
								,ui.getWeixinOpenid());
					}
				}
			}
			map.put("err_code",0);
			map.put("err_msg", "已向"+  list.size()  +"位用户发送课程包会员即将到期提醒");
		}
		
		return map;
	}

	@Override
	public Object hasPayCoursepackage(Integer userId) {
		Map<String,Object> map = new HashMap<String,Object>();
		if (userId==null) {
			map.put("err_code",400);
			map.put("err_msg", "参数异常");
			return map;
		}
		int count = coursePackageVipDao.hasPayCoursepackage(userId);
		if (count>0) { //有购买过
			map.put("err_code",0);
			map.put("err_msg", "该用户购买过课程包");
		}else {
			map.put("err_code",1);
			map.put("err_msg", "该用户未购买课程包");
		}
		return map;
	}

    @Override
    public Object queryUserPaidCPByUserid(CoursePackageVip vip) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (vip.getUserId() == null) {
            map.put("err_code", 400);
            map.put("err_msg", "参数异常");
            return map;
        }
        List<CoursePackageInfoDTO> coursePackageInfoDTOS = coursePackageVipDao.queryUserPaidCPByUserid(vip);

        for (CoursePackageInfoDTO coursePackageInfoDTO : coursePackageInfoDTOS) {
            if (coursePackageInfoDTO.getIsSpecial().equals("1")) {
                vip.setUserId(null);
                vip.setCoursePackageId(coursePackageInfoDTO.getId());
                vip.setIsVipStatus(1);
                int total = coursePackageVipDao.queryByCount(vip);

                coursePackageInfoDTO.setLearnerNum(total);
            }
        }

        if (coursePackageInfoDTOS.size() > 0) { //有购买过
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", coursePackageInfoDTOS);
        } else {
            map.put("err_code", 0);
            map.put("err_msg", "查询失败");
            map.put("rows", "");
        }
        return map;
    }

}
